<template>
  <div v-loading="loadBg"
       element-loading-text="拼命加载中"
       element-loading-background="rgba(0, 0, 0, 1)"
       element-loading-spinner="el-icon-loading">
    <div class="login-wrapper"
         v-if="!technicianBoolen"
         :style="
			indexData?.login_background_url 
			  ? {
				  'background-image':
					'url(' + indexData?.login_background_url + ')'
				}
			  : { 'background-image': 'url(' + backgrounds + ')' }
		  ">
      <div :class="[
			  'copyrightStatement',
			  { 'hidden-sm-and-down': styleResponsive }
			]"
           v-if="isOnLine ">
        电话 :{{ indexData?.platform_phone ? indexData?.platform_phone : '***********' }}
        │ 地址 :
        {{ indexData?.platform_address ? indexData?.platform_address : '***********' }} │
        版权信息∶{{
			  indexData?.site_version
				? indexData?.site_version
				: '*************'
			}}
        │ <span v-if="indexData?.network_record_number?true:false">
          京公网备案号︰<span @click="publicNetworkRecordNumberFn(indexData?.network_record_number?'https://beian.mps.gov.cn/#/query/webSearch':false)">{{
			  indexData?.network_record_number
	
				? indexData?.network_record_number
	
				: '*************'
			}}</span>
        </span>
        |<span v-if="indexData?.record_number?true:false">
          备案号︰<span @click="recordNumberFn(indexData?.record_number?'https://beian.miit.gov.cn/':false)">
            {{
			  indexData?.record_number
  
				? indexData?.record_number
	
	
				: '*************'
			}}
          </span>
        </span>
        | 客服二维码
        <img class="serviceQrCode"
             :src="
				indexData?.customer_qr
				  ? indexData?.customer_qr
				  : require('@/assets/bg-login.jpg')
			  "
             alt="" />
      </div>
      <el-card shadow="always"
               class="login-card">
        <div class="login-cover"
             :style="
				indexData?.background_login_img
				  ? {
					  'background-image':
						'url(' + indexData?.background_login_img + ')'
					}
				  : { 'background-image': 'url(' + backgroundsTwo + ')' }
			  ">
        </div>
        <div :class="['siteIcon', { 'hidden-sm-and-down': styleResponsive }]"
             :style="
				indexData?.login_left_logo
				  ? {
					  'background-image':
						'url(' + indexData?.login_left_logo + ')'
					}
				  : ''
			  ">
        </div>

        <div class="login-body">
          <h1 class="login-title">欢迎登录{{ is_platform?'主站':'子站' }}</h1>
          <h4 class="login-subtitle">WELCOME TO LOGIN</h4>
          <el-form ref="form"
                   size="large"
                   :model="form"
                   :rules="rules">
            <el-form-item prop="username">
              <el-input clearable
                        v-model="form.username"
                        @keyup.enter.native="submit"
                        placeholder="请输入登录账号"
                        prefix-icon="el-icon-user" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input show-password
                        v-model="form.password"
                        @keyup.enter.native="submit"
                        placeholder="请输入登录密码"
                        prefix-icon="el-icon-lock" />
            </el-form-item>
            <el-form-item prop="code">
              <div class="login-captcha-group">
                <el-input clearable
                          v-model="form.code"
                          placeholder="请输入验证码"
                          @keyup.enter.native="submit"
                          prefix-icon="el-icon-_vercode" />
                <div class="login-captcha"
                     @click="changeCaptcha">
                  <img v-if="captcha"
                       :src="captcha" />
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button size="large"
                         type="primary"
                         round
                         :loading="loading"
                         style="width: 70%"
                         @click="submit">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

  </div>
</template>
	
	<script>
// 获取站点info
import Cookies from 'js-cookie';



import { getSiteDomainName } from '@/api/siteList/index';
import { getToken } from '@/utils/token-util';
import { login, getCaptcha, installDataBase } from '@/api/login';
import { config } from '@/api/config/index'

export default {
  name: 'Login',
  components: {},
  data () {
    return {
      loadBg: true,
      // 登录框方向, 0居中, 1居右, 2居左
      direction: 0,
      // 加载状态
      loading: false,
      // 表单数据
      form: {
        username: '',
        password: '',
        remember: false,
        code: ''
      },
      // 验证码base64数据
      captcha: '',
      //   验证码内容, 实际项目去掉
      text: '',
      siteId: '',
      isOnLine: false,
      isMainOnline: false,
      indexData: null,
      indexMainData: null,
      backgrounds: require('@/assets/bg-login.jpg'),
      backgroundsTwo: require('@/assets/bg-login.jpg'),
      loginLeftLogo: require('@/assets/bg-login.jpg'),

      technicianBoolen: false,
      currentSoftwareStatus: '',
      is_platform: true,
    };
  },

  computed: {
    // 表单验证规则
    rules () {
      return {
        username: [
          {
            required: true,
            message: this.$t('login.username'),
            type: 'string',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('login.password'),
            type: 'string',
            trigger: 'blur'
          }
        ]
      };
    },
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    }
  },

  created () {
    // let host = 1
    // let host = window.location.host;
    // let origin = window.location.origin;

    this.querys();
    // 1 :总端 2:商家端 3：代理端  ———— 默认登录背景+左侧图片
    //   this.backgrounds = host=='dspkk.weijuyunke.com' ? require('/src/assets/allBj.png') : host=='oemkk.weijuyunke.com' ? require('/src/assets/loginBj.jpg') : require('/src/assets/agentBj.jpg')
    //   this.leftIcons = host=='dspkk.weijuyunke.com' ? require('/src/assets/allLeft2.png') : host=='oemkk.weijuyunke.com' ? require('/src/assets/leftIcon2.png') : require('/src/assets/agentLeft.jpg')
    //     console.log("window==========",'http://'+host.split(':')[0])
    if (getToken()) {
      this.goHome();
    } else {
      this.changeCaptcha();
    }
    this.getCookie();


  },
  methods: {
    async initDataBaseFn () {
      const res = await installDataBase()
      console.log(res.length)
      // 如果没有安装 0 不需要安装  1 需要安装
      if (res.code == 0) {
        return true
      } else {
        return false
      }

    },
    publicNetworkRecordNumberFn (url) {
      if (url) {
        window.open(url, '_blank');
        // window.location.href = url;
      }
    },
    recordNumberFn (url) {
      if (url) {
        window.open(url, '_blank');
        // window.location.href = url;
      }
    },
    /* 提交 */
    async submit () {
      if (this.form.remember) {
        console.log('存数据=============');
        Cookies.set('zhuUsername', this.form.username, { expires: 600 });
        Cookies.set('zhuPassword', this.form.password, { expires: 600 });
        Cookies.set('zhuRemember', this.form.remember, { expires: 600 });
      } else {
        // 否则移除
        Cookies.remove('zhuUsername');
        Cookies.remove('zhuPassword');
        Cookies.remove('zhuRemember');
      }



      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false;
        }

        if (this.form.code.toLowerCase() !== this.text) {
          this.$message.error('验证码错误');
          return;
        }

        this.loading = true;
        login(this.form)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.goHome();
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });

      });
    },
    async querys () {
      const result = await getSiteDomainName({
        // siteDomainName: 'yy.kunda5518.xyz'
        // siteDomainName: 'yjyksaas.admin168.net'
        // siteDomainName: ''
        // siteDomainName: window.location.host
      }).catch(() => { });
      console.log(result);
      if (result.code == 0) {
        if (result.data.is_platform == 0) {
          this.is_platform = true

          this.init();
        } else {
          this.is_platform = false
          //   子站
          this.init();
        }
      }


    },
    async init () {

      // 查询回显
      config()
        .then((msg) => {
          console.log(msg.data);
          if (msg.data) {
            // 浏览器图标
            // browser_logo: '',
            // // 系统图标
            // system_logo: '',
            // // 备案号
            // record_number: '',

            // // 京公网备案号
            // network_record_number: '',
            // // 版权信息
            // site_version: '',
            // // 登录背景图
            // login_background_url: '',
            // //登录左侧图标
            // login_left_logo: '',
            // //客服二维码
            // customer_qr: '',
            // // 手机号
            // phone: '',
            // // 邮箱
            // platform_email: '',
            // // 地址
            // platform_address: '',
            // // 平台电话
            // platform_phone: '',
            // // 上班时间
            // work_time: '',
            // // 版本号

            // // 系统名字
            // system_name: '',

            // //  公众号二维码
            // gongzonghao_qr_code: '',
            // // 公众号图片
            // gongzonghao_icon: '',
            // // 技术支持
            // skill_name: '',
            // // 交易规则
            // transaction_rule: '',
            // // 收银名称
            // cashier_name: '',
            // // 分享标题
            // distribution_title: '',
            // // 分享海报
            // distribution_instructions: '',
            // // 分享海报
            // distribution_poster: ''



            this.indexData = msg.data;

            localStorage.setItem('indexData', JSON.stringify(this.indexData)); // 存储 “系统图标等”
            // let item = JSON.parse(localStorage.getItem('indexData'))
            this.isOnLine =
              this.indexData?.site_version ||
                this.indexData.network_record_number ||
                this.indexData.record_number ||

                this.indexData.phone ||
                this.indexData.platform_address
                ? true
                : false;
            // 设置动态标题
            document.title = this.indexData.system_name;
            // 设置动态link图标（icon)
            var link =
              document.querySelector("link[rel*='icon']") ||
              document.createElement('link');
            link.type = 'image/x-icon';
            link.rel = 'shortcut icon';
            link.href = this.indexData.browser_logo
              ? this.indexData.browser_logo
              : require('@/assets/bg-login.jpg');
            document.getElementsByTagName('head')[0].appendChild(link);
          }
          this.loadBg = false;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },


    /* 跳转到首页 */
    goHome () {

      this.$router.push(this.$route?.query?.from ?? '/').catch(() => { });
    },
    /* 更换图形验证码 */
    changeCaptcha () {
      // 这里演示的验证码是后端返回base64格式的形式, 如果后端地址直接是图片请参考忘记密码页面
      getCaptcha()
        .then((data) => {
          this.captcha = data.base64;
          // 实际项目后端一般会返回验证码的key而不是直接返回验证码的内容, 登录用key去验证, 可以根据自己后端接口修改
          this.text = data.text;
          // 自动回填验证码, 实际项目去掉这个
          //   this.form.code = this.text;
          this.$refs?.form?.clearValidate();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    getCookie () {
      console.log('取数据=============');
      const usernames = Cookies.get('zhuUsername');
      const passwords = Cookies.get('zhuPassword');
      const remembers = Cookies.get('zhuRemember');
      console.log(usernames);
      console.log(passwords);
      console.log(remembers);
      this.form.username =
        usernames === undefined ? this.form.username : usernames;
      this.form.password =
        passwords === undefined ? this.form.password : passwords;
      this.form.remember =
        remembers === undefined ? this.form.remember : Boolean(remembers);
    }
  }
};
	</script>
	<style lang="scss" scoped>
.login-wrapper {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  //   background-image: url('/src/assets/images/网络登录.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  .login-card {
    width: 920px;
    max-width: 100%;
    overflow: hidden;
    .siteIcon {
      //   background-image: url('/src/assets/images/网络登录_03.png');
      background-repeat: no-repeat;
      background-size: 60%;
      position: absolute;
      height: 101px;
      width: 329px;
      top: 5.5%;
      transform: translate(-57px, -8px);
      z-index: 9999;
    }
    :deep(.el-card__body) {
      padding: 0;
      height: 462px;
    }
  }
}
.copyrightStatement {
  color: #fff;
  position: absolute;
  font-size: 16px;
  bottom: 24px;
  .serviceQrCode {
    margin-left: 10px;
    vertical-align: middle;
    width: 100px;
    height: 100px;
  }
}
.login-cover {
  position: absolute;
  -webkit-box-flex: 1;
  /* z-index: -1; */
  -ms-flex: 1;
  flex: 1;
  padding: 36px 8px;
  width: 590px;
  height: 463px;
  max-width: 100%;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background-repeat: no-repeat;
  background-position: bottom;
  background-size: cover;
  text-align: center;
  margin-left: 370px;
}

.login-body {
  width: 400px;
  flex-shrink: 0;
  padding: 32px 48px 0 48px;
  box-sizing: border-box;

  :deep(.el-checkbox) {
    height: auto;

    .el-checkbox__label {
      color: inherit;
    }
  }

  :deep(.el-input__prefix-inner > .el-icon) {
    margin-right: 12px;
    transform: scale(1.26) translateY(-1px);
  }
}

// 验证码
.login-captcha-group {
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.el-input) {
    flex: 1;
  }

  .login-captcha {
    width: 108px;
    height: 40px;
    margin-left: 8px;
    border-radius: 4px;
    border: 1px solid hsla(0, 0%, 60%, 0.46);
    transition: border 0.2s;
    box-sizing: border-box;
    background: #fff;
    overflow: hidden;
    cursor: pointer;

    img {
      width: calc(100% + 4px);
      height: calc(100% + 4px);
      margin: -2px 0 0 -2px;
      display: block;
    }

    &:hover {
      border-color: hsla(0, 0%, 60%, 0.8);
    }
  }

  :deep(.el-input__prefix-inner > .el-icon) {
    transform: scale(1.16);
  }
}

// 标题
.login-title {
  color: #007af5;
  font-weight: 700;
  font-size: 26px;
  margin: 0 0 0px 0;

  font-family: 'AliPuHui';
  letter-spacing: 1.2px;
}

.login-subtitle {
  color: #333333;
  font-size: 17px;
  margin: 0;
  font-weight: 700;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  letter-spacing: 4px;
  margin-bottom: 20px;
}
:deep(.el-icon) {
  color: #007af5;
}
/* 阿里巴巴普惠体 */
@font-face {
  font-family: 'AliPuHui';
  font-weight: 300;
  src: (
    url('//at.alicdn.com/wf/webfont/jWZHcEP2lzge/5AfKUTWZEo8W.woff2')
      format('woff2'),
    url('//at.alicdn.com/wf/webfont/jWZHcEP2lzge/Dvhs41TtRdYF.woff')
      format('woff')
  );
  font-display: swap;
}

// 二维码
.login-qrcode-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0;
}

.login-qrcode {
  font-size: 0;
  display: inline-block;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

// 小屏幕适应
@media screen and (max-width: 680px) {
  .login-wrapper {
    padding: 0;
    display: block;
    background: #fff;

    .login-card {
      width: 100%;
      background: none;
      box-shadow: none;
      border-radius: 0;

      :deep(.el-card__body) {
        display: block;
        height: auto;
      }
    }
  }

  .login-cover {
    padding: 24px 12px 100px 12px;
    background-size: auto 100px;
  }

  .login-body {
    width: 100%;
  }
}
</style>
	
	<style lang="scss">
html.dark .login-wrapper {
  background: #000;
  filter: brightness(0.88);
}
</style>
	